//
//  ST_RectangleMyLoveController.swift
//  btvideo
//
//  Created by mac on 2020/9/19.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import MJRefresh
import SwiftyJSON
import SwiftyAttributes
import SwiftyUserDefaults


class ST_RectangleMyLoveController: UIViewController{
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = Color.clear
        
         
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.refresh_data()
        })
        
        binding()
        
    }
    private func binding(){
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_data), name: Notification.Name.refresh_sweet_heart, object: nil)
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().withUnretained(self).subscribe(onNext: { own,f in
            print("SCComponets.login_status_did_changed_observable()")
            if f == true{
                own.refresh_data()
            }else{
                own.clear_data()
            }
            
        }).disposed(by: rx.disposeBag)
    }
    
    
    @objc func refresh_data(){
        
        self.currentPage = 0
        self.request_data()
        
    }
    
    
    @objc func clear_data(){
        
        
        UNREAD_LOVE_OF_MEET = 0
        data_array.removeAll()
        
        self.collectionView.reloadData()
        
        self.collectionView.mj_footer?.endRefreshing()
    }
    
    fileprivate func empty_view_handle(){
     
        
        if self.data_array.count < 1{
            
            let control = ST_BTEmptyView.init(title: "喜欢了这里才会有数据哦", imageName: ST_ImageUtils.imageName("喜欢_img_喜欢(空)")!)
            
            self.collectionView.show_bitian_empty(view: control)
            
        }else{
            self.collectionView.hidden_bitian_empty_view()
        }
    }
    
    fileprivate var total = 0
    
    fileprivate func request_data() {
        
        
        if ST_BTUserInfoManager.shared.current_account_info?.token.count ?? 0 < 2{
            return
        }
        
        currentPage += 1
        
        
        var param = ["page":currentPage,
                     "size":pageSize] as [String : Any]
        
        
        ST_ChatModuleViewController.shared.curr_filter.conver_to_param().forEach { (item) in
            param.updateValue(item.value, forKey: item.key)
        }
        
        JVrequest(PH.fetchFollowListApi,parameters: param ,success: { (json) in
            
            
            print("227272727272----",json)
            
            let data = json["data"]
            
            self.total = data["total"].intValue
            
            var count = 0
            
            let list = data["list"].arrayValue.map { (itemJson) -> ST_MyFansCellModel in
                return ST_MyFansCellModel.init(fromJson: itemJson)
            }
            
            if self.currentPage == 1{
                self.data_array = list
            }else{
                self.data_array += list
            }
            
            count = list.count
            
            self.empty_view_handle()
            
            self.collectionView.reloadData()
            
            self.load_more_option_style(tableView: self.collectionView, count: count, pageSize: self.pageSize) {
                
                self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                    
                    self?.request_data()
                })
            }
            
            self.collectionView.mj_footer?.endRefreshing()
            
            self.collectionView.mj_header?.endRefreshing()
            
        }) { (code, err) in
            
            self.toast(text: err)
            
            self.collectionView.mj_footer?.endRefreshing()
            self.collectionView.mj_header?.endRefreshing()
        }
        
        
    }
    
    //    MARK:- Properties
    
    
    
    var currentPage = 0
    
    fileprivate var data_array = [ST_MyFansCellModel]()
    
    fileprivate var pageSize = 15
    
    //     MARK: - Properties
    
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        let controlLayout = UICollectionViewFlowLayout()
        controlLayout.minimumLineSpacing = 15
        controlLayout.minimumInteritemSpacing = 15
        controlLayout.sectionInset = UIEdgeInsets.init(top: 12, left: 15, bottom: BTSafeAreaBottom + 49, right: 15)
        let w = (ScreenWidth - 15*3)/2
        controlLayout.itemSize = CGSize.init(width: w, height: w/165*160+70)
        controlLayout.headerReferenceSize = CGSize.init(width: ScreenWidth, height: 40)
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_RectangleMyLoveCell.self)
        
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: RectangleLoveMeHeaderView.self)
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.backgroundColor = Color.init(hexString: "#F5F8FA")
        control.alwaysBounceVertical = true
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
}


// MARK: UICollectionViewDataSource
extension ST_RectangleMyLoveController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    
    
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_RectangleMyLoveCell.self, for: indexPath)
        
        cell.model = data_array[safe:indexPath.item]
        
        return cell
    }
    
    // MARK: UICollectionViewDelegate
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        guard let m = data_array[safe:indexPath.item] else{
            return
        }
        
        let vc = ST_PairsCenterViewController()
        
        vc.accid = m.accid
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: RectangleLoveMeHeaderView.self, for: indexPath)
        
        if total < 1{
            
            view.content_label.attributedText = NSAttributedString()
            
            return view
        }
        
        var s = "我喜欢了".withAttributes([Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)),Attribute.textColor(UIColor.init(hex: 0x333333)!)])
        
        let n = total.string.withAttributes([Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)),Attribute.textColor(UIColor.init(hex: 0xFEC207)!)])
        
        
        let p = "人".withAttributes([Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)),Attribute.textColor(UIColor.init(hex: 0x333333)!)])
        
        s += n
        s += p
        
        view.content_label.attributedText = s
        
        return view
    }
    
}



//MARK: - Cell
class ST_RectangleMyLoveCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = Color.white
        
        contentView.addSubview(cover_image_view)
        contentView.addSubview(gradient_view)
        contentView.addSubview(time_label)
        contentView.addSubview(titleLabel)
        contentView.addSubview(content_label)
        contentView.addSubview(like_btn)
        
        
        contentView.cornerRadius = 20
        
        cover_image_view.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(cover_image_view.snp.width).dividedBy(165.0/160.0)
        }
        
        gradient_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(40)
            make.bottom.equalTo(cover_image_view)
        }
        
        time_label.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(cover_image_view).offset(-5)
        }
        
        
        
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(cover_image_view.snp.bottom).offset(13)
            make.height.equalTo(17)
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10-30-5)
        }
        
        
        content_label.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(8)
            make.left.equalTo(titleLabel)
        }
        
        like_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(40)
            make.right.equalToSuperview().offset(-5)
            make.bottom.equalToSuperview().offset(-15)
        }
        
        refresh_love_botton()
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_love_botton), name: Notification.Name.pairs_prop_updated, object: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //    MARK: - Properties
    
    fileprivate lazy var cover_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.clipsToBounds = true
        return control
    }()
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#333333")
        //        control.numberOfLines = 0
        //        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()
    
    
    fileprivate lazy var time_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.white
        //        control.numberOfLines = 0
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
    
    
    fileprivate lazy var gradient_view:ST_FWGradientView = {
        let control = ST_FWGradientView()
        
        control.bgLayer.colors = [UIColor(red: 0.12, green: 0.12, blue: 0.12, alpha: 0).cgColor, UIColor(red: 0, green: 0, blue: 0, alpha: 0.4).cgColor]
        control.bgLayer.locations = [0, 1]
        control.bgLayer.startPoint = CGPoint(x: 0, y: 0)
        //        [UIColor(red: 0.12, green: 0.12, blue: 0.12, alpha: 0).cgColor, UIColor(red: 0.02, green: 0.02, blue: 0.02, alpha: 0.2).cgColor, UIColor(red: 0, green: 0, blue: 0, alpha: 0.4).cgColor]
        
        control.bgLayer.endPoint = CGPoint(x: 0, y: 1)
        return control
    }()
    
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#61666F")
        //        control.numberOfLines = 0
        //        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate lazy var props_exchange_view:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("lovePropExchangeIcon")!)
        return control
    }()
    
    lazy var like_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImageForAllStates(ST_ImageUtils.imageName("MagicLoveButtonMagicIcon")!)
        
        control.addTarget(self, action: #selector(open_magic_tools_handle(sender:)), for: UIControl.Event.touchUpInside)
        
        
        return control
    }()
    
    //    MARK:-
    weak var model:ST_MyFansCellModel?{
        didSet{
            
            guard let m = model else{
                return
            }
            
            
            
            cover_image_view.pin_setImage(from: m.avatar.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            titleLabel.text = m.nickname
            
            time_label.text = m.hb_time.double.b_t_global_date_string()
            
            content_label.text = m.age.string + "岁" + " \(m.address)"
            
            
            refresh_love_botton()
        }
    }
    
}

//MARK: - Event
//
extension ST_RectangleMyLoveCell{
    
    @objc func refresh_love_botton(){
        
        /*
         guard let m = self.model , m.isSentProps == false else {
         
         like_btn.isHidden = true
         
         return
         }*/
        
        like_btn.isHidden = true
        
        //        like_btn.propUrl = nil
        //
        //        if like_btn.propUrl != nil{
        //            if props_exchange_view.superview == nil,like_btn.superview != nil {
        //                contentView.addSubview(props_exchange_view)
        //                props_exchange_view.snp.makeConstraints { (make) in
        //                    make.width.equalTo(101)
        //                    make.height.equalTo(40)
        //                    make.right.equalToSuperview()
        //                    make.bottom.equalTo(self.like_btn.snp.top).offset(5)
        //                }
        //            }
        //        }else{
        //
        //            props_exchange_view.removeFromSuperview()
        //        }
        
    }
    
    @objc func chat_handle(){
        
    }
    
    @objc fileprivate func open_magic_tools_handle(sender:UIControl){
        
        
        let vc = ST_SendAirshipViewController()
        
        vc.overCurrentContext = true
        
        vc.send_closure = {[weak self] m in
            self?.send_air_ship(model: m)
        }
        
        GlobalPresent(toController: vc)
        
    }
    
    @objc fileprivate func send_like_handle(sender:UIControl){
        
        push_to_remote_like_action(id: nil)
        
    }
    
    fileprivate func send_air_ship(model:ST_ChooseAirshipCellModel){
        
        
        let vc = ST_PairsPropBrowserController()
        
        vc.overCurrentContext = true
        
        vc.animationIndex = model.id
        
        vc.play_completion_closure = { [weak self] in
            
            self?.push_to_remote_like_action(id: model.id.string)
            
        }
        
        GlobalPresent(toController: vc, animated: false)
        
    }
    
    
    fileprivate func push_to_remote_like_action(id:String? = nil){
        
        
        guard let model = self.model else{
            return
        }
        
        
        let info = ST_MatchUserInfo(accid: model.accid, avatar: model.avatar, nickname: model.nickname)
        
        self.like_btn.isUserInteractionEnabled = false
        
        
        
        PairsLikeAction(info: info, likeAction: true, isReceive: false, fromVC: self.parentViewController,propId:id) { (code, err , matched) in
            
            self.like_btn.isUserInteractionEnabled = true
            
            if code == 1{
                
                matched?()
                
                //                self.viewModel.tableHeaderViewModel.is_attention = true
                //                self.operate_after_handle()
                
                self.refresh_love_botton()
                
                
            }else {
                
                if let e = err{ self.parentViewController?.toast(text: e) }
                
            }
        }
        
        
    }
    
}


//MARK: - 魔法棒
class ST_MagicLoveButton: UIControl {
    
    
    
    fileprivate let heilBackgroundImageName = "heilBackgroundBackgroundImage"
    
    fileprivate let normalIcon = ST_ImageUtils.imageName("MagicLoveButtonMagicIcon")!
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(background_image_view)
        background_image_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        self.addSubview(icon_image_view)
        icon_image_view.snp.makeConstraints { (make) in
            make.width.height.equalToSuperview().dividedBy(4.0/3.0)
            make.center.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    fileprivate lazy var background_image_view:UIImageView = {
        let control = UIImageView.init(image: UIImage.init(named: heilBackgroundImageName))
        return control
    }()
    
    fileprivate lazy var icon_image_view:UIImageView = {
        let control = UIImageView.init(image: normalIcon)
        //        control.backgroundColor = .random
        return control
    }()
    
    var propUrl:String?{
        didSet{
            
            if let url = propUrl?.url{
                icon_image_view.pin_setImage(from: url)
            }else{
                icon_image_view.image = normalIcon
            }
            
        }
    }
}
